<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="脱粒日期">
        <el-date-picker v-model="daterangeCreateTime" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
          range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item label="打玉米人" prop="cornUser">
        <el-input v-model="queryParams.cornUser" placeholder="请输入打玉米人" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="操作人" prop="operateUser">
        <el-select v-model="queryParams.operateUser" placeholder="请选择操作人" clearable>
          <el-option v-for="dict in dict.type.operate_user" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['food:corn:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['food:corn:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['food:corn:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['food:corn:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="cornList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="打玉米人" align="center" prop="cornUser" />
      <el-table-column label="单位" align="center" prop="unit">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.weight_unit" :value="scope.row.unit" />
        </template>
      </el-table-column>
      <el-table-column label="斤数" align="center" prop="foodWeight" />
      <el-table-column label="单价" align="center" prop="foodPrice" />
      <el-table-column label="总额" align="center" prop="totalPrice" />

      <el-table-column label="操作人" align="center" prop="operateUser">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.operate_user" :value="scope.row.operateUser" />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="用户地址" align="center" prop="userAddress" />
      <el-table-column label="脱粒日期" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{m}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['food:corn:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['food:corn:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改玉米脱粒记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="打玉米人" prop="cornUser">
          <el-input v-model="form.cornUser" placeholder="请输入打玉米人姓名" />
        </el-form-item>
        <el-form-item label="操作人" prop="operateUser">
          <el-select v-model="form.operateUser" placeholder="请选择操作人">
            <el-option v-for="dict in dict.type.operate_user" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-select v-model="form.unit" placeholder="请选择单位">
            <el-option v-for="dict in dict.type.weight_unit" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="斤数" prop="foodWeight" @input="calculateTotal">
          <el-input v-model="form.foodWeight" placeholder="请输入斤数" />
        </el-form-item>
        <el-form-item label="单价" prop="foodPrice">
          <el-input v-model="form.foodPrice" placeholder="请输入单价" @input="calculateTotal" />
        </el-form-item>
        <el-form-item label="总额" prop="totalPrice">
          <el-input v-model="form.totalPrice" placeholder="请输入总额" />
        </el-form-item>

        

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="用户地址" prop="userAddress">
          <el-input v-model="form.userAddress" placeholder="请输入用户地址" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
        <el-button @click="toggleRecording">{{ isRecording ? '停止录音' : '开始录音' }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCorn, getCorn, delCorn, addCorn, updateCorn } from "@/api/food/corn";
import { getWord } from "@/api/food/entry";
import HZRecorder from '@/utils/HZRecorder'

export default {
  name: "Corn",
  dicts: ['operate_user', 'weight_unit'],
  data() {
    return {
      isRecording: false,
      recognition: null,
      recordedText: '',
      recorder: null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 玉米脱粒记录表格数据
      cornList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // $comment时间范围
      daterangeCreateTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        cornUser: null,
        operateUser: null,
        createTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        cornUser: [
          { required: true, message: "打玉米人不能为空", trigger: "blur" }
        ],
        foodWeight: [
          { required: true, message: "斤数不能为空", trigger: "blur" }
        ],
        foodPrice: [
          { required: true, message: "单价不能为空", trigger: "blur" }
        ],
        totalPrice: [
          { required: true, message: "总额不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 初始化navigator
    initMedia() {
      if (navigator.mediaDevices.getUserMedia || navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia) {
        this.getUserMedia({ video: false, audio: true }) // 调用用户媒体设备，访问摄像头、录                    音
      } else {
        console.log('你的浏览器不支持访问用户媒体设备')
      }
    },
    async getUserMedia(constraints) {
      try {
        let mediaAPI;
        if (navigator.mediaDevices?.getUserMedia) {
          mediaAPI = navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);
        } else {
          mediaAPI = (navigator.webkitGetUserMedia ||
            navigator.mozGetUserMedia ||
            navigator.getUserMedia).bind(navigator);
        }

        const stream = await mediaAPI(constraints);
        this.recorder = new HZRecorder(stream);
        console.log('Recorder initialized successfully');
        return stream;
      } catch (error) {
        console.error('Microphone access failed:', error);
        this.$message.error('无法访问麦克风，请检查浏览器权限设置');
        throw error;
      }
    },
    // 成功的回调函数
    success(stream) {
      console.log('已点击允许,开启成功')
    },
    // 异常的回调函数 
    error(error) {
      console.log('访问用户媒体设备失败：', error.name, error.message)
    },
    // Update the startRecording method
    async startRecording() {
      try {
        if (!this.recorder) {
          await this.getUserMedia({ audio: true });
        }
        this.recorder.start();
        this.isRecording = true;
        this.$message.success('录音已开始');
      } catch (error) {
        console.error('Recording start failed:', error);
        this.isRecording = false;
        this.recorder = null;
      }
    },
    // 修改 stopRecording 方法
    stopRecording() {
      let audioBlob = null;
      if (this.recorder) {
        audioBlob = this.recorder.getBlob();
        console.log('Recorded audio blob:', audioBlob);
        this.recorder.stop();
        this.recorder = null;

        // 创建FormData并添加文件
        const formData = new FormData();
        formData.append('file', audioBlob, 'recording.wav');

        getWord(formData).then(response => {
          console.log('Upload successful:', response);
          if (response) {
            this.form.cornUser = response;
          }
        }).catch(error => {
          console.error('Upload failed:', error);
          this.$message.error('语音识别失败');
        });
      }
      this.isRecording = false;
    },

    async toggleRecording() {
      if (this.isRecording) {
        this.stopRecording();
      } else {
        await this.startRecording();
      }
    },
    // 计算总额
    calculateTotal() {
      this.form.totalPrice = Math.round(parseFloat(this.form.foodWeight) * parseFloat(this.form.foodPrice) * 100) / 100;
    },
    /** 查询玉米脱粒记录列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
        this.queryParams.params["beginCreateTime"] = this.daterangeCreateTime[0];
        this.queryParams.params["endCreateTime"] = this.daterangeCreateTime[1];
      }
      listCorn(this.queryParams).then(response => {
        this.cornList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        cornUser: null,
        foodWeight: null,
        foodPrice: null,
        unit: null,
        operateUser: null,
        totalPrice: null,
        remark: null,
        userAddress: null,
        delFlag: null,
        createTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeCreateTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加玉米脱粒记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCorn(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改玉米脱粒记录";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCorn(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCorn(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除玉米脱粒序号为"' + ids + '"的数据项？').then(function () {
        return delCorn(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('food/corn/export', {
        ...this.queryParams
      }, `corn_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
